from django import newforms as forms
from django.shortcuts import render_to_response
from erlydb import ErlySocialInterface
from simplereg.models import CouchDBServer
import twitter

try:
    set
except NameError:
    from sets import Set as set

class TwitterLoginForm(forms.Form):
    username = forms.CharField(max_length=128)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput)
    for_username = forms.CharField(max_length=128)

def findfriends(request):
    form = TwitterLoginForm(request.POST or None)
    context = {'form': form, 'logged_in':False}
    if form.is_valid():
        api = twitter.Api(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
        erlysocial = ErlySocialInterface(CouchDBServer.objects.get_url())
        tfriends = api.GetFriends(form.cleaned_data['for_username'])
        twitter_friends = set("http://twitter.com/%s" % f.screen_name for f in tfriends)
        es_friends = set(erlysocial.get_friends_from_url("http://twitter.com/%s" % form.cleaned_data['for_username']))
        href_name = {}
        for friend in tfriends:
            href_name["http://twitter.com/%s" % friend.screen_name] = friend.name
        for friend in es_friends:
            s = friend.split("http://twitter.com/")
            if len(s) > 0:
                href_name[friend] = s[1]
        context['friends'] = [(href_name[f],f) for f in es_friends - twitter_friends]
        context['logged_in'] = True
    return render_to_response('twitterfriend/findfriends.html', context)